package own.application.system.config;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.shiro.mgt.SecurityManager;

import own.application.system.shiro.MyRealm;

@Configuration
public class ShiroConfiguration {
	
	@Bean
	public MyRealm myRealm(){
		return new MyRealm();
	}
	
	@Bean
	public CacheManager cacheManager(){
		return new MemoryConstrainedCacheManager();
	}
	
	@Bean
	public SecurityManager securityManager(MyRealm myRealm,CacheManager cacheManager){
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setCacheManager(cacheManager);
		securityManager.setRealm(myRealm);
		return securityManager;
	}
	
	@Bean
	public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
		ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
		shiroFilter.setSecurityManager(securityManager);
		shiroFilter.setLoginUrl("/login");
		shiroFilter.setUnauthorizedUrl("/login");
		Map<String,String> filterChainDefinitions = new LinkedHashMap<String,String>();
		filterChainDefinitions.put("/login", "anon");
		filterChainDefinitions.put("/check_login", "anon");
		filterChainDefinitions.put("/home", "authc");
		filterChainDefinitions.put("/context/**/*", "authc");
		filterChainDefinitions.put("/resources/**", "anon");
		shiroFilter.setFilterChainDefinitionMap(filterChainDefinitions);
		return shiroFilter;
	}
}
